package composite;

import java.util.ArrayList;
import java.util.List;

interface Iterator{
    void iteratorTree(Node node, int deep);
}

abstract class Node{
    String name;
    abstract void print();
}

class LeafNode extends Node{
    LeafNode(String name){
        this.name = name;
    }

    @Override
    void print() {
        System.out.println(name);
    }
}

class BranchNode extends Node{
    BranchNode(String name){
        this.name = name;
    }

    List<Node> list = new ArrayList<>();

    BranchNode addNode(Node node){
        list.add(node);
        return this;
    }

    @Override
    void print() {
        System.out.println(name);
    }

    Iterator iterator(){
        return new Iterator() {
            @Override
            public void iteratorTree(Node node, int deep) {
                for(int i = 0; i < deep; i++){
                    System.out.print("--");
                }
                node.print();
                if(node instanceof BranchNode){
                    for(Node node1 : ((BranchNode) node).list){
                        this.iteratorTree(node1, deep+1);
                    }
                }
            }
        };
    }
}


public class Composite {
    public static void main(String[] args) {
        BranchNode root = new BranchNode("root");
        BranchNode leftBranchNode = new BranchNode("leftBranchNode");
        BranchNode rightBranchNode = new BranchNode("rightBranchNode");

        LeafNode  leftLeafNode = new LeafNode("leftLeafNode");
        LeafNode rightLeafNode = new LeafNode("rightLeafNode");

        root.addNode(leftBranchNode).addNode(rightBranchNode).addNode(new LeafNode("leaf"));
        leftBranchNode.addNode(leftLeafNode);
        rightBranchNode.addNode(rightLeafNode);

        root.iterator().iteratorTree(root, 0);
    }
}
